package com.spring.core;

/**
 * Copyright (c) 2018-2023 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * @author liyuncong
 * @version 1.0
 * @file SpringProperties
 * @brief SpringProperties
 * @details SpringProperties
 * @date 2023-01-13
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2023-01-13                  liyuncong          Created
 */
public final class SpringProperties {

    private static final String PROPERTIES_RESOURCE_LOCATION = "spring.properties";

    private static final Properties localProperties = new Properties();

    static {
        try {
            ClassLoader classLoader = SpringProperties.class.getClassLoader();
            URL url = (classLoader != null ? classLoader.getResource(PROPERTIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResource(PROPERTIES_RESOURCE_LOCATION));
            if (url != null) {
                try (InputStream inputStream = url.openStream()) {
                    localProperties.load(inputStream);
                }
            }
        } catch (IOException exception) {
            System.err.println(
                "Could not load 'spring.properties' file from local classpath: " + exception);
        }
    }

    public static String getProperty(String key) {
        String value = localProperties.getProperty(key);
        if (value == null) {
            try {
                value = System.getProperty(key);
            } catch (Throwable throwable) {
                System.err.println("Could not retrieve system property '" + key + "':" + throwable);
            }
        }
        return value;
    }

    public static void setFlag(String key) {
        localProperties.put(key, Boolean.TRUE.toString());
    }

    public static boolean getFlag(String key) {
        return Boolean.parseBoolean(getProperty(key));
    }
}
